package edu.del.springbootredisbusinesspractice.web.controller;

import edu.del.springbootredisbusinesspractice.commons.exception.OrderException;
import edu.del.springbootredisbusinesspractice.pojo.Orders;
import edu.del.springbootredisbusinesspractice.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单相关接口
 */
@Slf4j
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private OrdersService ordersService;

    /**
     * 下单接口 - 使用RequestBody接收参数
     */
    @PostMapping("/place")
    public ResponseEntity<Map<String, Object>> placeOrder(
            @RequestBody Map<String, Object> request) {

        Integer productId = (Integer) request.get("productId");
        Integer count = (Integer) request.get("count");

        if (productId == null || productId <= 0 || count == null || count <= 0) {
            throw new OrderException(400, "参数错误：productId 和 count 必须为正整数");
        }

        int orderId = ordersService.placeOrder(productId, count);

        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "下单成功");
        result.put("data", orderId);

        return ResponseEntity.ok(result);
    }

    /**
     * 支付成功回调接口
     */
    @PostMapping("/pay/success")
    public ResponseEntity<Map<String, Object>> paySuccess(@RequestParam String orderNo) {
        try {
            boolean result = ordersService.paySuccess(orderNo);

            Map<String, Object> response = new HashMap<>();
            if (result) {
                response.put("code", 200);
                response.put("message", "支付成功");
                response.put("data", null);
            } else {
                response.put("code", 500);
                response.put("message", "支付状态更新失败");
                response.put("data", null);
            }
            return ResponseEntity.ok(response);

        } catch (OrderException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", e.getErrorCode());
            errorResponse.put("message", e.getMessage());
            errorResponse.put("data", null);
            return ResponseEntity.ok(errorResponse);
        }
    }

    /**
     * 根据订单ID获取订单详情
     */
    @GetMapping("/{orderId}")
    public ResponseEntity<Orders> getOrderById(@PathVariable Integer orderId) {
        Orders order = ordersService.getById(orderId);
        if (order != null) {
            return ResponseEntity.ok(order);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 新增：取消订单接口
    @PostMapping("/cancel")
    public ResponseEntity<Map<String, Object>> cancelOrder(@RequestParam String orderNo) {
        try {
            boolean result = ordersService.cancelOrder(orderNo);
            Map<String, Object> response = new HashMap<>();
            if (result) {
                response.put("code", 200);
                response.put("message", "订单已取消");
            } else {
                response.put("code", 500);
                response.put("message", "订单取消失败");
            }
            return ResponseEntity.ok(response);
        } catch (OrderException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", e.getErrorCode());
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.ok(errorResponse);
        }
    }

    // 新增：查询是否有订单未支付
    @GetMapping("/hasUnpaid/{id}")
    public ResponseEntity<Map<String, Object>> hasUnpaidOrder(@PathVariable Integer id) {
        List<Orders> result = ordersService.UnpaidOrderList(id);
        log.info("【查询是否有订单未支付】查询结果：{}", result);
        Map<String, Object> response = new HashMap<>();
        if (result != null && !result.isEmpty()) {
            response.put("code", 200);
            response.put("message", "有未支付订单");
            response.put("data", result);
        } else {
            response.put("code", 404);
            response.put("message", "没有未支付订单");
            response.put("data", null);
        }
        return ResponseEntity.ok(response);
    }
}